<template>
	<div class="search-filter-wrap" v-if="datas && datas.length > 0">
		<div class="search-picker-title">{{title}}</div>
		<div class="search-picker-item-group">
			<span v-if="unlimited" @click="clear" class="picker-item" :class="{selected: isEmpty}">不限</span>
			<span v-for="d of datas" @click="change(d)" :key="d[keyName]" :class="{selected: isSelected(d)}" class="picker-item">{{d[titleName]}}</span>
			<slot></slot>
		</div>
	</div>
</template>

<script>
import Utils from 'hey-utils';
export default {
	props: {
		title: String,
		datas: Array,
		prop: String,
		value: Object,
		unlimited: {
			type: Boolean,
			default: true
		},
		multiple: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			keyName:'id',
			titleName:'name'
		}
	},
	mounted() {
		if(this.datas && this.datas.length > 0 && this.datas[0].key && this.datas[0].title){
			this.keyName = 'key'
			this.titleName = 'title'
		}
	},
	methods: {
		isSelected(data) {
			if (this.multiple) {
				if(this.nowValue && this.nowValue.length > 0){
					return this.nowValue.indexOf(data[this.keyName]) > -1
				}else if (data[this.keyName] == 0){
					return true
				}
			} else {
				return this.nowValue == data[this.keyName]
			}
		},
		change(data) {
			let result = null;
			if (this.multiple) {
				if(data[this.keyName] > 0){
					result = this.nowValue || []
					let index = -1
					result.forEach((v,k)=>{
						if(v == data[this.keyName]){
							index = k
						}
					})
					if(index > -1){
						result.splice(index,1)
					}else{
						result.push(data[this.keyName])
					}
				}else{
					result = []
				}
			} else {
				result = data[this.keyName]
			}
			this.setvalue(result)
		},
		clear() {
			if (this.multiple) {
				this.setvalue([])
			} else {
				this.setvalue(0)
			}
		},
		setvalue(data) {
			let value = Utils.copy(this.value)
			value[this.prop] = data
			this.$emit('input',value)
		}
	},
	computed: {
		isEmpty() {
			return !this.nowValue || this.nowValue.length == 0
		},
		nowValue() {
			return this.value[this.prop]
		}
	}
}
</script>

<style lang='less'>
.search-filter-wrap {
	display: flex;
	margin-bottom: 10px;
	.search-picker-title {
		font-weight: bold;
		line-height: 32px;
		color: rgba(0, 0, 0, 0.65);
		width: 60px;
		margin-right: 15px;
		color: rgba(0,0,0,.85);
	}
	.search-picker-item-group {
		flex: 1;
		display: flex;
		flex-wrap: wrap;
	}
	.picker-item {
		cursor: pointer;
		margin: 2px;
		padding: 4px 8px;
		border-radius: 2px;
		transition: 0.2s;
		&:hover, &.selected {
			background: @primary-color;
			color: #FFF;
		}
	}
}
</style>